import random
from datetime import datetime

from django.db import transaction
from django.utils import timezone
from drf_spectacular.utils import extend_schema
from rest_framework import status, filters
from rest_framework.decorators import action
from rest_framework.response import Response
from apps.data.schemas import DownloadResponse, UploadRequest, UploadResponse

from apps.clsbb.filters import *
from apps.clsbb.model.check_models import *
from apps.clsbb.serializers import *
from apps.system.models import Dict_item, Company
from extensions.permissions import IsAuthenticated
from extensions.viewsets import *
from django.db.models import Count, Q
from apps.common.models import Pagination


class Clsbbfak_RecordsViewSet(ModelViewSet, ExportMixin, ImportMixin):
    """七库全书"""
    queryset = Clsbbfak_Records.objects.all()
    serializer_class = Clsbbfak_RecordsSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = Clsbbfak_RecordsFilter
    search_fields = ['keywords']
    select_related_fields = ['company', 'filled_by', 'next_checker',]
    # prefetch_related_fields = ['check_records','downloads_records','views_records']
    prefetch_related_fields = ['check_records',]
    ordering_fields = ['id', 'name','is_effective','add_time','downloads','views',]

    def add_record(self,serializer):
        clsbbfak = serializer.save()
        clsbbfak_check = ClsbbfakCheck.objects.create(
            clsbbfak=clsbbfak, check_user=self.user,
            opinion=self.request.data['opinion'],
            is_agree=self.request.data['is_agree'])
        clsbbfak.check_records.add(clsbbfak_check)

    @action(detail=False, methods=['get'])
    def add_downloads_log(self,request, *args, **kwargs):
        id = self.request.query_params.get('id', None)
        clsbbfak_quereset = Clsbbfak_Records.objects.filter(id=id)
        clsbbfak=clsbbfak_quereset[0]
        downloads_log = Downloads_log.objects.create(
            clsbbfak=clsbbfak, download_by=self.user,)
        clsbbfak.downloads_log.add(downloads_log)
        downloads_count =Downloads_log.objects.filter(clsbbfak_id=id).count()
        clsbbfak_quereset.update(downloads=downloads_count)

        return Response(data={'downloads_count':downloads_count}, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def add_views_log(self,request, *args, **kwargs):
        id = self.request.query_params.get('id', None)
        clsbbfak_quereset = Clsbbfak_Records.objects.filter(id=id)
        clsbbfak=clsbbfak_quereset[0]
        views_log = Views_log.objects.create(
            clsbbfak=clsbbfak, view_by=self.user,)
        clsbbfak.views_log.add(views_log)
        views_count =Views_log.objects.filter(clsbbfak_id=id).count()
        clsbbfak_quereset.update(views=views_count)

        return Response(data={'views_count':views_count}, status=status.HTTP_200_OK)


    @transaction.atomic
    def perform_create(self,serializer):
        self.add_record(serializer)

    @transaction.atomic
    def perform_update(self, serializer):
        self.add_record(serializer)


    @action(detail=False, methods=['get'])
    def waitMeModify(self, request, *args, **kwargs):
        """待我修改"""
        query =Q(filled_by=self.user) & Q(is_effective=-1)
        queryset = Clsbbfak_Records.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('name')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeCheck(self, request, *args, **kwargs):
        """待我审核"""
        query =Q(next_checker=self.user) & Q(is_effective=0)
        queryset = Clsbbfak_Records.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('name')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    def get_pdfinstance(self,Clsbbfak_item,pdf_type):
        if pdf_type in Clsbbfak_item:
            query = Q(id=Clsbbfak_item[pdf_type])
            Clsbbfak_item[pdf_type] = Clsbb_Common_Pdfs.objects.filter(query)[0]
            return Clsbbfak_item[pdf_type]
        return None
    

    @extend_schema(responses={200: DownloadResponse})
    @action(detail=False, methods=['get'])
    def import_template(self, request, *args, **kwargs):
        """导入模板"""
        return self.get_template_response(Clsbbfak_RecordsImportSerializer,"方案库导入模板")


    @extend_schema(request=UploadRequest, responses={200: UploadResponse})
    @action(detail=False, methods=['post'])
    @transaction.atomic
    def import_data(self, request, *args, **kwargs):
        """导入数据"""
        request_serializer = UploadRequest(data=request.data)
        request_serializer.is_valid(raise_exception=True)
        validated_data = request_serializer.validated_data
        import_serializer = self.load_data(validated_data['file'], Clsbbfak_RecordsImportSerializer)
        try:
            import_serializer.is_valid(raise_exception=True)
        except Exception as e:
            return Response(status=status.HTTP_400_BAD_REQUEST, data={'error': str(e)})
        Clsbbfak_Records_items = import_serializer.validated_data
        update_count = 0
        create_count = 0
        for Clsbbfak_Records_item in Clsbbfak_Records_items:
            dict_items = ['classification','industry']
            for dict_item in dict_items:
                item= Clsbbfak_Records_item.get(dict_item, None)
                print("item:",item)
                Clsbbfak_Records_item[dict_item] = self.get_import_data_dict_instance(item)
                print("Clsbbfak_Records_item[dict_item]:",Clsbbfak_Records_item[dict_item])
            Clsbbfak_Records_item['step'] = 3
            Clsbbfak_Records_item['is_effective'] = 1
            name= Clsbbfak_Records_item['name']
            company = Clsbbfak_Records_item.get('company', None)
            Clsbbfak_Records_item['company'] = self.get_import_data_company_instance(company)
            clsbbfak_records = Clsbbfak_Records.objects.filter(name__icontains=name).first()
            #获附件实例
            attachment = Clsbb_Common_Pdfs.objects.filter(name__icontains=name).first()
            #如果Clsbbfak_Records_item['cbsp_bi']为空，则返回错误信息
            if not attachment:
                return Response(status=status.HTTP_400_BAD_REQUEST, data={'error': "方案名为“{}”的附件不存在".format(name)})
            else:
                Clsbbfak_Records_item['attachments_scheme'] = attachment
            if clsbbfak_records:
                Clsbbfak_Records.objects.filter(name__icontains=name).update(**Clsbbfak_Records_item)
                update_count += 1
            else:
                Clsbbfak_Records_item['filled_by'] = self.user
                Clsbbfak_Records_item['number'] =self.generate_number_unique_id(company)
                clsbbfak_records = Clsbbfak_Records.objects.create(**Clsbbfak_Records_item)
                create_count += 1

        return Response(status=status.HTTP_200_OK, data={'update_count': update_count,
                                                         'create_count': create_count,
                                                         })

    #获取导入数据的公司实例
    def get_import_data_company_instance(self, company):
        try:
            if company:
                return Company.objects.get(Q(name__icontains=company))
            else:
                return self.user.company
        except Company.DoesNotExist:
            return self.user.company

    #自动生成方案编号
    def generate_number_unique_id(self,company):
        company_instance = self.get_import_data_company_instance(company)
        prefix = company_instance.coding_abbreviation+'_FAK'
        date = timezone.now().strftime('%Y%m%d')
        unique_id = random.randint(10 ** 6, 10 ** 7 - 1)
        number_unique_id = prefix + date + str(unique_id)
        while Clsbbfak_Records.objects.filter(number=number_unique_id).exists():
            unique_id = random.randint(10 ** 6, 10 ** 7 - 1)
        number_unique_id = prefix + date + str(unique_id)
        return number_unique_id

    #获取导入数据的数据字典实例
    def get_import_data_dict_instance(self, dict_item):
        print("dict_item:",dict_item)
        try:
            if dict_item:
                instance = Dict_item.objects.filter(Q(name=dict_item) & Q(description__contains='clsbb')).first()
                if instance:
                    return instance
                else:
                    instance = Dict_item.objects.filter(Q(id=dict_item) | Q(name=dict_item) | Q(name__icontains=dict_item)).first()
                    return instance
            else:
                return None
        except Dict_item.DoesNotExist:
            return None


class Clsbbalk_RecordsViewSet(ModelViewSet, ExportMixin, ImportMixin):
    """七库全书案例库"""
    queryset = Clsbbalk_Records.objects.all()
    serializer_class = Clsbbalk_RecordsSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = Clsbbalk_RecordsFilter
    search_fields = ['keywords']
    select_related_fields = ['company', 'filled_by', 'next_checker',]
    # prefetch_related_fields = ['check_records','downloads_records','views_records']
    prefetch_related_fields = ['check_records',]
    ordering_fields = ['id', 'name','is_effective','add_time','downloads','views',]

    def add_record(self,serializer):
        clsbbalk = serializer.save()
        clsbbalk_check = ClsbbalkCheck.objects.create(
            clsbbalk=clsbbalk, check_user=self.user,
            opinion=self.request.data['opinion'],
            is_agree=self.request.data['is_agree'])
        clsbbalk.check_records.add(clsbbalk_check)

    @action(detail=False, methods=['get'])
    def add_downloads_log(self,request, *args, **kwargs):
        id = self.request.query_params.get('id', None)
        clsbbalk_quereset = Clsbbalk_Records.objects.filter(id=id)
        clsbbalk=clsbbalk_quereset[0]
        downloads_log = Alk_Downloads_log.objects.create(
            clsbbalk=clsbbalk, download_by=self.user,)
        clsbbalk.downloads_log.add(downloads_log)
        downloads_count =Alk_Downloads_log.objects.filter(clsbbalk_id=id).count()
        clsbbalk_quereset.update(downloads=downloads_count)

        return Response(data={'downloads_count':downloads_count}, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def add_views_log(self,request, *args, **kwargs):
        id = self.request.query_params.get('id', None)
        clsbbalk_quereset = Clsbbalk_Records.objects.filter(id=id)
        clsbbalk=clsbbalk_quereset[0]
        views_log = Alk_Views_log.objects.create(
            clsbbalk=clsbbalk, view_by=self.user,)
        clsbbalk.views_log.add(views_log)
        views_count =Alk_Views_log.objects.filter(clsbbalk_id=id).count()
        clsbbalk_quereset.update(views=views_count)

        return Response(data={'views_count':views_count}, status=status.HTTP_200_OK)


    @transaction.atomic
    def perform_create(self,serializer):
        self.add_record(serializer)

    @transaction.atomic
    def perform_update(self, serializer):
        self.add_record(serializer)


    @action(detail=False, methods=['get'])
    def waitMeModify(self, request, *args, **kwargs):
        """待我修改"""
        query =Q(filled_by=self.user) & Q(is_effective=-1)
        queryset = Clsbbalk_Records.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('name')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeCheck(self, request, *args, **kwargs):
        """待我审核"""
        query =Q(next_checker=self.user) & Q(is_effective=0)
        queryset = Clsbbalk_Records.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('name')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    def get_pdfinstance(self,Clsbbfak_item,pdf_type):
        if pdf_type in Clsbbfak_item:
            query = Q(id=Clsbbfak_item[pdf_type])
            Clsbbfak_item[pdf_type] = Clsbb_Common_Pdfs.objects.filter(query)[0]
            return Clsbbfak_item[pdf_type]
        return None
    


    @extend_schema(responses={200: DownloadResponse})
    @action(detail=False, methods=['get'])
    def import_template(self, request, *args, **kwargs):
        """导入模板"""
        return self.get_template_response(Clsbbalk_RecordsImportSerializer,"案例库导入模板")


    @extend_schema(request=UploadRequest, responses={200: UploadResponse})
    @action(detail=False, methods=['post'])
    @transaction.atomic
    def import_data(self, request, *args, **kwargs):
        """导入数据"""
        request_serializer = UploadRequest(data=request.data)
        request_serializer.is_valid(raise_exception=True)
        validated_data = request_serializer.validated_data
        import_serializer = self.load_data(validated_data['file'], Clsbbalk_RecordsImportSerializer)
        try:
            import_serializer.is_valid(raise_exception=True)
        except Exception as e:
            return Response(status=status.HTTP_400_BAD_REQUEST, data={'error': str(e)})
        Clsbbalk_Records_items = import_serializer.validated_data
        update_count = 0
        create_count = 0
        for Clsbbalk_Records_item in Clsbbalk_Records_items:
            dict_items = ['industry','product']
            for dict_item in dict_items:
                item= Clsbbalk_Records_item.get(dict_item, None)
                Clsbbalk_Records_item[dict_item] = self.get_import_data_dict_instance(item)
            Clsbbalk_Records_item['step'] = 3
            Clsbbalk_Records_item['is_effective'] = 1
            name= Clsbbalk_Records_item['name']
            company = Clsbbalk_Records_item.get('company', None)
            Clsbbalk_Records_item['company'] = self.get_import_data_company_instance(company)
            clsbbalk_records = Clsbbalk_Records.objects.filter(name__icontains=name).first()
            #获附件实例
            attachment = Clsbb_Common_Pdfs.objects.filter(name__icontains=name).first()
            #如果Clsbbalk_Records_item['cbsp_bi']为空，则返回错误信息
            if not attachment:
                return Response(status=status.HTTP_400_BAD_REQUEST, data={'error': "案例名为“{}”的附件不存在".format(name)})
            else:
                Clsbbalk_Records_item['attachments_case'] = attachment
            if clsbbalk_records:
                Clsbbalk_Records.objects.filter(name__icontains=name).update(**Clsbbalk_Records_item)
                update_count += 1
            else:
                Clsbbalk_Records_item['filled_by'] = self.user
                Clsbbalk_Records_item['number'] =self.generate_number_unique_id(company)
                clsbbalk_records = Clsbbalk_Records.objects.create(**Clsbbalk_Records_item)
                create_count += 1

        return Response(status=status.HTTP_200_OK, data={'update_count': update_count,
                                                         'create_count': create_count,
                                                         })

    #获取导入数据的公司实例
    def get_import_data_company_instance(self, company):
        try:
            if company:
                return Company.objects.get(Q(name__icontains=company))
            else:
                return self.user.company
        except Company.DoesNotExist:
            return self.user.company

    #自动生成案例编号
    def generate_number_unique_id(self,company):
        company_instance = self.get_import_data_company_instance(company)
        prefix = company_instance.coding_abbreviation+'_ALK'
        date = timezone.now().strftime('%Y%m%d')
        unique_id = random.randint(10 ** 6, 10 ** 7 - 1)
        number_unique_id = prefix + date + str(unique_id)
        while Clsbbalk_Records.objects.filter(number=number_unique_id).exists():
            unique_id = random.randint(10 ** 6, 10 ** 7 - 1)
        number_unique_id = prefix + date + str(unique_id)
        return number_unique_id

    #获取导入数据的数据字典实例
    def get_import_data_dict_instance(self, dict_item):
        print("dict_item:",dict_item)
        try:
            if dict_item:
                instance = Dict_item.objects.filter(Q(name=dict_item) & Q(description__contains='clsbb')).first()
                if instance:
                    return instance
                else:
                    instance = Dict_item.objects.filter(Q(id=dict_item) | Q(name=dict_item) | Q(name__icontains=dict_item)).first()
                    return instance
            else:
                return None
        except Dict_item.DoesNotExist:
            return None


class Clsbbtbk_RecordsViewSet(ModelViewSet, ExportMixin, ImportMixin):
    """七库全书投标库"""
    queryset = Clsbbtbk_Records.objects.all()
    serializer_class = Clsbbtbk_RecordsSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = Clsbbtbk_RecordsFilter
    search_fields = ['keywords']
    select_related_fields = ['company', 'filled_by', 'next_checker',]
    # prefetch_related_fields = ['check_records','downloads_records','views_records']
    prefetch_related_fields = ['check_records',]
    ordering_fields = ['id', 'name','is_effective','add_time','downloads','views',]

    def add_record(self,serializer):
        clsbbtbk = serializer.save()
        clsbbtbk_check = ClsbbtbkCheck.objects.create(
            clsbbtbk=clsbbtbk, check_user=self.user,
            opinion=self.request.data['opinion'],
            is_agree=self.request.data['is_agree'])
        clsbbtbk.check_records.add(clsbbtbk_check)

    @action(detail=False, methods=['get'])
    def add_downloads_log(self,request, *args, **kwargs):
        id = self.request.query_params.get('id', None)
        clsbbtbk_quereset = Clsbbtbk_Records.objects.filter(id=id)
        clsbbtbk=clsbbtbk_quereset[0]
        downloads_log = Tbk_Downloads_log.objects.create(
            clsbbtbk=clsbbtbk, download_by=self.user,)
        clsbbtbk.downloads_log.add(downloads_log)
        downloads_count =Tbk_Downloads_log.objects.filter(clsbbtbk_id=id).count()
        clsbbtbk_quereset.update(downloads=downloads_count)

        return Response(data={'downloads_count':downloads_count}, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def add_views_log(self,request, *args, **kwargs):
        id = self.request.query_params.get('id', None)
        clsbbtbk_quereset = Clsbbtbk_Records.objects.filter(id=id)
        clsbbtbk=clsbbtbk_quereset[0]
        print('clsbbtbk_quereset:',clsbbtbk_quereset)
        views_log = Tbk_Views_log.objects.create(
            clsbbtbk=clsbbtbk, view_by=self.user,)
        clsbbtbk.views_log.add(views_log)
        views_count =Tbk_Views_log.objects.filter(clsbbtbk_id=id).count()
        clsbbtbk_quereset.update(views=views_count)

        return Response(data={'views_count':views_count}, status=status.HTTP_200_OK)


    @transaction.atomic
    def perform_create(self,serializer):
        self.add_record(serializer)

    @transaction.atomic
    def perform_update(self, serializer):
        self.add_record(serializer)


    @action(detail=False, methods=['get'])
    def waitMeModify(self, request, *args, **kwargs):
        """待我修改"""
        query =Q(filled_by=self.user) & Q(is_effective=-1)
        queryset = Clsbbtbk_Records.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('name')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeCheck(self, request, *args, **kwargs):
        """待我审核"""
        query =Q(next_checker=self.user) & Q(is_effective=0)
        queryset = Clsbbtbk_Records.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('name')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    def get_pdfinstance(self,Clsbbfak_item,pdf_type):
        if pdf_type in Clsbbfak_item:
            query = Q(id=Clsbbfak_item[pdf_type])
            Clsbbfak_item[pdf_type] = Clsbb_Common_Pdfs.objects.filter(query)[0]
            return Clsbbfak_item[pdf_type]
        return None



class Clsbbcpk_RecordsViewSet(ModelViewSet, ExportMixin, ImportMixin):
    """七库全书产品库"""
    queryset = Clsbbcpk_Records.objects.all()
    serializer_class = Clsbbcpk_RecordsSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = Clsbbcpk_RecordsFilter
    search_fields = ['name']
    select_related_fields = ['company', 'filled_by', 'next_checker',]
    prefetch_related_fields = ['check_records',]
    ordering_fields = ['id', 'name','is_effective','add_time','downloads','views',]

    def add_record(self,serializer):
        clsbbcpk = serializer.save()
        clsbbcpk_check = ClsbbcpkCheck.objects.create(
            clsbbcpk=clsbbcpk, check_user=self.user,
            opinion=self.request.data['opinion'],
            is_agree=self.request.data['is_agree'])
        clsbbcpk.check_records.add(clsbbcpk_check)

    @action(detail=False, methods=['get'])
    def add_downloads_log(self,request, *args, **kwargs):
        id = self.request.query_params.get('id', None)
        clsbbcpk_quereset = Clsbbcpk_Records.objects.filter(id=id)
        clsbbcpk=clsbbcpk_quereset[0]
        downloads_log = Cpk_Downloads_log.objects.create(
            clsbbcpk=clsbbcpk, download_by=self.user,)
        clsbbcpk.downloads_log.add(downloads_log)
        downloads_count =Cpk_Downloads_log.objects.filter(clsbbcpk_id=id).count()
        clsbbcpk_quereset.update(downloads=downloads_count)

        return Response(data={'downloads_count':downloads_count}, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def add_views_log(self,request, *args, **kwargs):
        id = self.request.query_params.get('id', None)
        clsbbcpk_quereset = Clsbbcpk_Records.objects.filter(id=id)
        clsbbcpk=clsbbcpk_quereset[0]
        print('clsbbcpk_quereset:',clsbbcpk_quereset)
        views_log = Cpk_Views_log.objects.create(
            clsbbcpk=clsbbcpk, view_by=self.user,)
        clsbbcpk.views_log.add(views_log)
        views_count =Cpk_Views_log.objects.filter(clsbbcpk_id=id).count()
        clsbbcpk_quereset.update(views=views_count)

        return Response(data={'views_count':views_count}, status=status.HTTP_200_OK)


    @transaction.atomic
    def perform_create(self,serializer):
        self.add_record(serializer)

    @transaction.atomic
    def perform_update(self, serializer):
        self.add_record(serializer)


    @action(detail=False, methods=['get'])
    def waitMeModify(self, request, *args, **kwargs):
        """待我修改"""
        query =Q(filled_by=self.user) & Q(is_effective=-1)
        queryset = Clsbbcpk_Records.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('name')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeCheck(self, request, *args, **kwargs):
        """待我审核"""
        query =Q(next_checker=self.user) & Q(is_effective=0)
        queryset = Clsbbcpk_Records.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('name')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    def get_pdfinstance(self,Clsbbfak_item,pdf_type):
        if pdf_type in Clsbbfak_item:
            query = Q(id=Clsbbfak_item[pdf_type])
            Clsbbfak_item[pdf_type] = Clsbb_Common_Pdfs.objects.filter(query)[0]
            return Clsbbfak_item[pdf_type]
        return None



class Clsbbhzhbk_RecordsViewSet(ModelViewSet, ExportMixin, ImportMixin):
    """七库全书产品库"""
    queryset = Clsbbhzhbk_Records.objects.all()
    serializer_class = Clsbbhzhbk_RecordsSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = Clsbbhzhbk_RecordsFilter
    search_fields = ['name','business_scope']
    select_related_fields = ['company', 'filled_by', 'next_checker',]
    prefetch_related_fields = ['check_records',]
    ordering_fields = ['id', 'name','is_effective','add_time','downloads','views',]

    def add_record(self,serializer):
        clsbbhzhbk = serializer.save()
        clsbbhzhbk_check = ClsbbhzhbkCheck.objects.create(
            clsbbhzhbk=clsbbhzhbk, check_user=self.user,
            opinion=self.request.data['opinion'],
            is_agree=self.request.data['is_agree'])
        clsbbhzhbk.check_records.add(clsbbhzhbk_check)

    @action(detail=False, methods=['get'])
    def add_downloads_log(self,request, *args, **kwargs):
        id = self.request.query_params.get('id', None)
        clsbbhzhbk_quereset = Clsbbhzhbk_Records.objects.filter(id=id)
        clsbbhzhbk=clsbbhzhbk_quereset[0]
        downloads_log = Hzhbk_Downloads_log.objects.create(
            clsbbhzhbk=clsbbhzhbk, download_by=self.user,)
        clsbbhzhbk.downloads_log.add(downloads_log)
        downloads_count =Hzhbk_Downloads_log.objects.filter(clsbbhzhbk_id=id).count()
        clsbbhzhbk_quereset.update(downloads=downloads_count)

        return Response(data={'downloads_count':downloads_count}, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def add_views_log(self,request, *args, **kwargs):
        id = self.request.query_params.get('id', None)
        clsbbhzhbk_quereset = Clsbbhzhbk_Records.objects.filter(id=id)
        clsbbhzhbk=clsbbhzhbk_quereset[0]
        print('clsbbhzhbk_quereset:',clsbbhzhbk_quereset)
        views_log = Hzhbk_Views_log.objects.create(
            clsbbhzhbk=clsbbhzhbk, view_by=self.user,)
        clsbbhzhbk.views_log.add(views_log)
        views_count =Hzhbk_Views_log.objects.filter(clsbbhzhbk_id=id).count()
        clsbbhzhbk_quereset.update(views=views_count)

        return Response(data={'views_count':views_count}, status=status.HTTP_200_OK)


    @transaction.atomic
    def perform_create(self,serializer):
        self.add_record(serializer)

    @transaction.atomic
    def perform_update(self, serializer):
        self.add_record(serializer)


    @action(detail=False, methods=['get'])
    def waitMeModify(self, request, *args, **kwargs):
        """待我修改"""
        query =Q(filled_by=self.user) & Q(is_effective=-1)
        queryset = Clsbbhzhbk_Records.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('name')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeCheck(self, request, *args, **kwargs):
        """待我审核"""
        query =Q(next_checker=self.user) & Q(is_effective=0)
        queryset = Clsbbhzhbk_Records.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('name')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    def get_pdfinstance(self,Clsbbfak_item,pdf_type):
        if pdf_type in Clsbbfak_item:
            query = Q(id=Clsbbfak_item[pdf_type])
            Clsbbfak_item[pdf_type] = Clsbb_Common_Pdfs.objects.filter(query)[0]
            return Clsbbfak_item[pdf_type]
        return None



class Clsbbgszzk_RecordsViewSet(ModelViewSet, ExportMixin, ImportMixin):
    """七库全书公司资质库"""
    queryset = Clsbbgszzk_Records.objects.all()
    serializer_class = Clsbbgszzk_RecordsSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = Clsbbgszzk_RecordsFilter
    search_fields = ['name']
    select_related_fields = ['company', 'filled_by', 'next_checker',]
    prefetch_related_fields = ['check_records',]
    ordering_fields = ['id', 'name','is_effective','add_time','downloads','views',]

    def add_record(self,serializer):
        clsbbgszzk = serializer.save()
        clsbbgszzk_check = ClsbbgszzkCheck.objects.create(
            clsbbgszzk=clsbbgszzk, check_user=self.user,
            opinion=self.request.data['opinion'],
            is_agree=self.request.data['is_agree'])
        clsbbgszzk.check_records.add(clsbbgszzk_check)

    @action(detail=False, methods=['get'])
    def add_downloads_log(self,request, *args, **kwargs):
        id = self.request.query_params.get('id', None)
        clsbbgszzk_quereset = Clsbbgszzk_Records.objects.filter(id=id)
        clsbbgszzk=clsbbgszzk_quereset[0]
        downloads_log = Gszzk_Downloads_log.objects.create(
            clsbbgszzk=clsbbgszzk, download_by=self.user,)
        clsbbgszzk.downloads_log.add(downloads_log)
        downloads_count =Gszzk_Downloads_log.objects.filter(clsbbgszzk_id=id).count()
        clsbbgszzk_quereset.update(downloads=downloads_count)

        return Response(data={'downloads_count':downloads_count}, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def add_views_log(self,request, *args, **kwargs):
        id = self.request.query_params.get('id', None)
        clsbbgszzk_quereset = Clsbbgszzk_Records.objects.filter(id=id)
        clsbbgszzk=clsbbgszzk_quereset[0]
        print('clsbbgszzk_quereset:',clsbbgszzk_quereset)
        views_log = Gszzk_Views_log.objects.create(
            clsbbgszzk=clsbbgszzk, view_by=self.user,)
        clsbbgszzk.views_log.add(views_log)
        views_count =Gszzk_Views_log.objects.filter(clsbbgszzk_id=id).count()
        clsbbgszzk_quereset.update(views=views_count)

        return Response(data={'views_count':views_count}, status=status.HTTP_200_OK)


    @transaction.atomic
    def perform_create(self,serializer):
        self.add_record(serializer)

    @transaction.atomic
    def perform_update(self, serializer):
        self.add_record(serializer)


    @action(detail=False, methods=['get'])
    def waitMeModify(self, request, *args, **kwargs):
        """待我修改"""
        query =Q(filled_by=self.user) & Q(is_effective=-1)
        queryset = Clsbbgszzk_Records.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('name')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeCheck(self, request, *args, **kwargs):
        """待我审核"""
        query =Q(next_checker=self.user) & Q(is_effective=0)
        queryset = Clsbbgszzk_Records.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('name')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    def get_pdfinstance(self,Clsbbfak_item,pdf_type):
        if pdf_type in Clsbbfak_item:
            query = Q(id=Clsbbfak_item[pdf_type])
            Clsbbfak_item[pdf_type] = Clsbb_Common_Pdfs.objects.filter(query)[0]
            return Clsbbfak_item[pdf_type]
        return None



class Clsbbryzzk_RecordsViewSet(ModelViewSet, ExportMixin, ImportMixin):
    """七库全书人员资质库"""
    queryset = Clsbbryzzk_Records.objects.all()
    serializer_class = Clsbbryzzk_RecordsSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = Clsbbryzzk_RecordsFilter
    search_fields = ['name']
    select_related_fields = ['company', 'filled_by', 'next_checker',]
    prefetch_related_fields = ['check_records',]
    ordering_fields = ['id', 'name','is_effective','add_time','downloads','views',]

    def add_record(self,serializer):
        clsbbryzzk = serializer.save()
        clsbbryzzk_check = ClsbbryzzkCheck.objects.create(
            clsbbryzzk=clsbbryzzk, check_user=self.user,
            opinion=self.request.data['opinion'],
            is_agree=self.request.data['is_agree'])
        clsbbryzzk.check_records.add(clsbbryzzk_check)

    @action(detail=False, methods=['get'])
    def add_downloads_log(self,request, *args, **kwargs):
        id = self.request.query_params.get('id', None)
        clsbbryzzk_quereset = Clsbbryzzk_Records.objects.filter(id=id)
        clsbbryzzk=clsbbryzzk_quereset[0]
        downloads_log = Ryzzk_Downloads_log.objects.create(
            clsbbryzzk=clsbbryzzk, download_by=self.user,)
        clsbbryzzk.downloads_log.add(downloads_log)
        downloads_count =Ryzzk_Downloads_log.objects.filter(clsbbryzzk_id=id).count()
        clsbbryzzk_quereset.update(downloads=downloads_count)

        return Response(data={'downloads_count':downloads_count}, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def add_views_log(self,request, *args, **kwargs):
        id = self.request.query_params.get('id', None)
        clsbbryzzk_quereset = Clsbbryzzk_Records.objects.filter(id=id)
        clsbbryzzk=clsbbryzzk_quereset[0]
        print('clsbbryzzk_quereset:',clsbbryzzk_quereset)
        views_log = Ryzzk_Views_log.objects.create(
            clsbbryzzk=clsbbryzzk, view_by=self.user,)
        clsbbryzzk.views_log.add(views_log)
        views_count =Ryzzk_Views_log.objects.filter(clsbbryzzk_id=id).count()
        clsbbryzzk_quereset.update(views=views_count)

        return Response(data={'views_count':views_count}, status=status.HTTP_200_OK)


    @transaction.atomic
    def perform_create(self,serializer):
        self.add_record(serializer)

    @transaction.atomic
    def perform_update(self, serializer):
        self.add_record(serializer)


    @action(detail=False, methods=['get'])
    def waitMeModify(self, request, *args, **kwargs):
        """待我修改"""
        query =Q(filled_by=self.user) & Q(is_effective=-1)
        queryset = Clsbbryzzk_Records.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('name')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeCheck(self, request, *args, **kwargs):
        """待我审核"""
        query =Q(next_checker=self.user) & Q(is_effective=0)
        queryset = Clsbbryzzk_Records.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('name')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    def get_pdfinstance(self,Clsbbfak_item,pdf_type):
        if pdf_type in Clsbbfak_item:
            query = Q(id=Clsbbfak_item[pdf_type])
            Clsbbfak_item[pdf_type] = Clsbb_Common_Pdfs.objects.filter(query)[0]
            return Clsbbfak_item[pdf_type]
        return None




class Clsbb_CommonPdfsViewSet(ModelViewSet):
    """Clsbb公共pdf"""

    serializer_class = Clsbb_Common_PdfsSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = Clsbb_Common_PdfsFilter
    search_fields = ['company__name', 'name']
    select_related_fields = ['company', 'filled_by']
    ordering_fields = ['id', 'name', 'add_time']
    queryset = Clsbb_Common_Pdfs.objects.all()

    @transaction.atomic
    def perform_destroy(self, instance):
        instance.file.delete(save=False)
        instance.delete()
        Response(status=status.HTTP_204_NO_CONTENT)